﻿using System;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Business;
using Entities;

namespace ServicesDirectory.UserControl
{
    public partial class ListService : System.Web.UI.UserControl
    {
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            Repeater1.ItemDataBound += Repeater1_ItemDataBound;
            Repeater1.ItemCommand += Repeater1_ItemCommand;
            cmdBackAll.Click += CmdFirst_Click;
            cmdBacklist.Click += CmdBack_Click;
            cmdNext.Click += CmdNext_Click;
            cmdNextAll.Click += CmdLast_Click;
            lbtAll.Click += All_Click;
            lbt09.Click += lbt09_Click;
            lbtA.Click += lbtA_Click;
            lbtF.Click += lbtF_Click;
            lbtK.Click += lbtK_Click;
            lbtO.Click += lbtO_Click;
            lbtS.Click += lbtS_Click;
            lbtW.Click += lbtW_Click;
            lbtServiceName.Click += LbtServiceName_Click;
            btnCopy.Click += BtnCopy_Click;
            cmdCreate.Click += CmdCreate_Click;
            chkInactive.CheckedChanged += ChkInactive_CheckedChanged;
            MessageBox1.Ok += MessageBox1_Ok;
              if (Request.QueryString["inactive"] != null)
            {
                var serviceId = new Guid(Request.QueryString["inactive"]);
                var result = ServiceBusiness.Instance.ChangeStatus(serviceId, false);
                if (result)
                {
                    Response.Redirect("ListService.aspx");
                }
            }
            if (Request.QueryString["log"] != null)
            {
                LogDataBusiness.Instance.Delete(Session.SessionID);
                Response.Redirect("ListService.aspx");
            }
            if (!IsPostBack)
            {
                Display();
            }
        }

        #region filter funtion - do filfer base on keyword
        void lbtW_Click(object sender, EventArgs e)
        {
            txtPageNumber.Text = "1";
            ViewState["btnFilter"] = "lbtW";
            ViewState["filter"] = "wz";
            Display();
        }

        void lbtS_Click(object sender, EventArgs e)
        {
            txtPageNumber.Text = "1";
            ViewState["btnFilter"] = "lbtS";
            ViewState["filter"] = "sv";
            Display();
        }

        void lbtO_Click(object sender, EventArgs e)
        {
            txtPageNumber.Text = "1";
            ViewState["btnFilter"] = "lbtO";
            ViewState["filter"] = "or";
            Display();
        }

        void lbtK_Click(object sender, EventArgs e)
        {
            txtPageNumber.Text = "1";
            ViewState["btnFilter"] = "lbtK";
            ViewState["filter"] = "kn";
            Display();
        }

        void lbtF_Click(object sender, EventArgs e)
        {
            txtPageNumber.Text = "1";
            ViewState["btnFilter"] = "lbtF";
            ViewState["filter"] = "fj";
            Display();
        }

        void lbtA_Click(object sender, EventArgs e)
        {
            txtPageNumber.Text = "1";
            ViewState["btnFilter"] = "lbtA";
            ViewState["filter"] = "ae";
            Display();
        }

        void lbt09_Click(object sender, EventArgs e)
        {
            txtPageNumber.Text = "1";
            ViewState["btnFilter"] = "lbt09";
            ViewState["filter"] = "09";
            Display();
        }

        void All_Click(object sender, EventArgs e)
        {
            txtPageNumber.Text = "1";
            ViewState["btnFilter"] = "lbtAll";
            ViewState["filter"] = "all";
            Display();
        }
        #endregion

        #region paging button
        protected void CmdFirst_Click(object sender, EventArgs e)
        {
            txtPageNumber.Text = "1";
            Display();
        }

        protected void CmdBack_Click(object sender, EventArgs e)
        {
            if (Int32.Parse(txtPageNumber.Text, CultureInfo.CurrentCulture) > 1)
            {
                txtPageNumber.Text = (Int32.Parse(txtPageNumber.Text, CultureInfo.CurrentCulture) - 1).ToString(CultureInfo.CurrentCulture);
            }
            Display();
        }

        protected void CmdNext_Click(object sender, EventArgs e)
        {
            if (Int32.Parse(txtPageNumber.Text, CultureInfo.CurrentCulture) < Int32.Parse(lblTotalPage.Text, CultureInfo.CurrentCulture))
            {
                txtPageNumber.Text =
                    (Int32.Parse(txtPageNumber.Text, CultureInfo.CurrentCulture) + 1).ToString(
                        CultureInfo.CurrentCulture);
            }
            Display();
        }

        protected void CmdLast_Click(object sender, EventArgs e)
        {
            txtPageNumber.Text = lblTotalPage.Text;
            Display();
        }
        #endregion

        #region function
        private void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Edit")
            {
                var lblIsactive = e.Item.FindControl("lblIsactive") as Label;
                if (lblIsactive != null)
                {
                    if (lblIsactive.Text == "Yes")
                    {
                        Session["serviceId"] = e.CommandArgument.ToString();
                        Response.Redirect("ServiceDetail.aspx?ServiceId=" + e.CommandArgument);
                    }
                    else
                    {
                        var script = "var result= window.confirm('Do you want to make this Service active?'); " +
                                     "if(result)" +
                                     " location.href=('ServiceDetail.aspx?active=" + e.CommandArgument + "');";
                        ScriptManager.RegisterClientScriptBlock(UpdatePanel1, typeof(UpdatePanel), UpdatePanel1.ClientID, script, true);
                    }
                }
            }
        }

        private void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {

            var lblIsactive = e.Item.FindControl("lblIsactive") as Label;
            var lblContact = e.Item.FindControl("lblContact") as Label;
            var lblServiceType = e.Item.FindControl("lblServiceType") as Label;
            if (lblServiceType != null)
            {
                var servicetype = ServiceBusiness.Instance.GetServiceType(Int32.Parse(lblServiceType.Text, CultureInfo.CurrentCulture));
                lblServiceType.Text = servicetype.Length > 13 ? servicetype.Substring(0, 13) + "..." : servicetype;
            }
            if (lblIsactive != null)
            {
                lblIsactive.Text = lblIsactive.Text == "True" ? "Yes" : "No";
            }
            if (lblContact != null)
            {
                string message;
                var contact = ContactBusiness.Instance.GetContact(lblContact.Text, out message);
                lblContact.Text = contact.FirstName + " " + contact.SurName;
            }

            var rdo = (RadioButton)e.Item.FindControl("rbtSelect");
            const string script = "SetUniqueRadioButton(this)";
            rdo.Attributes.Add("onclick", script);
        }

        private void Display()
        {
            pnPaging.Visible = true;
            Collection<Service> colServices;
            if (ViewState["btnFilter"] != null)
            {
                ((LinkButton) FindControl(ViewState["btnFilter"].ToString())).ForeColor = Color.FromName("#99ff00");
            }
            if (ViewState["filter"] == null)
            {
                colServices = ServiceBusiness.Instance.Filter("all", chkInactive.Checked);
            }
            else
            {
                colServices = ServiceBusiness.Instance.Filter(ViewState["filter"].ToString(), chkInactive.Checked);
            }

            if (ViewState["sort"] != null)
            {
                if (ViewState["sort"].ToString().Equals("asc"))
                {
                    colServices = new Collection<Service>(colServices.OrderBy(item => item.ServiceName).ToList());
                }
                else
                {
                    colServices =
                        new Collection<Service>(colServices.OrderByDescending(item => item.ServiceName).ToList());
                }
            }

            
            if (colServices.Count > 0)
            {
                pnNoRecord.Visible = false;
                colServices = Paging(colServices);
                Repeater1.DataSource = colServices;
                Repeater1.DataBind();
            }
            else
            {
                Repeater1.DataSource = null;
                Repeater1.DataBind();
                pnNoRecord.Visible = true;
                pnPaging.Visible = false;
            }
        }

        private Collection<Service> Paging(Collection<Service> listServices)
        {
            lblTotalPage.Text = (listServices.Count % 10 == 0 ? listServices.Count / 10 : listServices.Count / 10 + 1).ToString(CultureInfo.InvariantCulture);
            //paging on list result
            var pagedList = ServiceBusiness.Instance.Paging(int.Parse(txtPageNumber.Text, CultureInfo.InvariantCulture), 10, listServices);
            return pagedList;
        }

        void MessageBox1_Ok(object sender, EventArgs e)
        {
            pnMessage.Visible = false;
        }

        private void CmdCreate_Click(object sender, EventArgs e)
        {
            Response.Redirect("ServiceDetail.aspx");
        }

        private void ChkInactive_CheckedChanged(object sender, EventArgs e)
        {
            Display();
        }

        private void BtnCopy_Click(object sender, EventArgs e)
        {
            bool selected = false;

            foreach (RepeaterItem item in Repeater1.Items)
            {
                var rdo = (RadioButton)item.FindControl("rbtSelect");
                var serviceId = (HiddenField)item.FindControl("hdfServiceId");
                if (rdo.Checked)
                {
                    selected = true;
                    Session["Copy"] = "copy";
                    Response.Redirect("ServiceDetail.aspx?ServiceId=" + serviceId.Value);
                    break;
                }

            }
            if (!selected)
            {
                //MessageBox1.ShowButton(2);
                //MessageBox1.SetTitle("Please select a Service to copy", 4);
                //pnMessage.Visible = true;
                const string alertcopy = "alert('Please select a Service to copy');";
                ScriptManager.RegisterClientScriptBlock(UpdatePanel1, typeof(UpdatePanel), "alertcopy", alertcopy, true);
            }
        }

        private void LbtServiceName_Click(object sender, EventArgs e)
        {
            if (ViewState["sort"] == null || ViewState["sort"].Equals("desc"))
            {
                ViewState["sort"] = "asc";
            }
            else
            {
                ViewState["sort"] = "desc";
            }
            Display();
        }
        #endregion
    }
}